﻿using JinYuan.Helper;
using JinYuan.Models;
using JinYuan.VirtualDataLibrary;
using PLCCommunication.Common;
using PLCCommunication.Common.DataConvert;
using System;

namespace JinYuan.ControlCenters
{
    public partial class ControlCenter
    {
        public static string GetValueFromByteArray(byte[] bArray, string PLCGroupVariablekey, int offset = 0, Group pf = null)
        {
            return GetValueFromByteArray(bArray, getPLCVariable(PLCGroupVariablekey), offset, pf);
        }

        public static PLCGroupVariable getPLCVariable(string key)
        {
            PLCGroupVariable pLCGroupVariable = new PLCGroupVariable();
            CommonMethods.PLCVariable.TryGetValue(key, out pLCGroupVariable);
            return pLCGroupVariable;
        }

        /// <summary>
        /// 获取MES返回结果
        /// </summary>
        /// <param name="bArray"></param>
        /// <param name="var"></param>
        /// <param name="offset"></param>
        /// <param name="pf"></param>
        /// <returns></returns>
        public static string GetValueFromByteArray(byte[] bArray, PLCGroupVariable var, int offset = 0, Group pf = null)
        {
            string value = "0";
            try
            {
                switch (var.DataType)
                {
                    case "Float":
                        value = FloatLib.GetFloatFromByteArray(bArray, var.ArrayStart * 2 + offset, DataFormat.CDAB).ToString("0.###");
                        break;
                    case "Short":
                        value = ShortLib.GetShortFromByteArray(bArray, var.ArrayStart * 2 + offset).ToString();
                        break;
                    case "Int":
                        value = IntLib.GetIntFromByteArray(bArray, var.ArrayStart * 2 + offset).ToString();
                        break;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteError($"数据解析异常, 原因: {ex}", "SysErrorLog");
            }
            return value;
        }
    }
}
